package com.yjf.ljr.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;

import com.yjf.ljr.R;
import com.yjf.ljr.onekeyshare.CustomerLogo;

public class ShareSDKAdapter extends BaseAdapter {

	private Context mContext;
	private LayoutInflater inflater;
	private ArrayList<Object> shareItems;

	public ShareSDKAdapter(Context ctx, ArrayList<Object> items) {
		mContext = ctx;
		inflater = LayoutInflater.from(mContext);
		shareItems = items;
	}

	@Override
	public int getCount() {
		return shareItems.size();
	}

	@Override
	public Object getItem(int position) {
		return shareItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ShareItemHolder viewHolder;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.share_dialog_item, null);
			viewHolder = new ShareItemHolder();
			viewHolder.logo = (ImageView) convertView.findViewById(R.id.share_icon);
			viewHolder.label = (TextView) convertView.findViewById(R.id.share_label);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ShareItemHolder) convertView.getTag();
		}

		Bitmap logo;
		String label;
		Object item = getItem(position);

		if (item instanceof Platform) {
			logo = getIcon((Platform) item);
			label = getName((Platform) item);
		} else {
			CustomerLogo customerLogo = (CustomerLogo) item;
			logo = customerLogo.enableLogo;
			label = customerLogo.label;
		}
		viewHolder.logo.setImageBitmap(logo);
		viewHolder.label.setText(label);

		return convertView;
	}

	class ShareItemHolder {
		public ImageView logo;
		public TextView label;
	}

	private Bitmap getIcon(Platform plat) {
		if (plat == null) {
			return null;
		}

		String name = plat.getName();
		if (name == null) {
			return null;
		}

		String resName = "logo_" + plat.getName();
		int resId = com.mob.tools.utils.R.getBitmapRes(mContext.getApplicationContext(), resName);
		return BitmapFactory.decodeResource(mContext.getResources(), resId);
	}

	private String getName(Platform plat) {
		if (plat == null) {
			return "";
		}

		String name = plat.getName();
		if (name == null) {
			return "";
		}

		int resId = com.mob.tools.utils.R.getStringRes(mContext.getApplicationContext(), plat.getName());
		if (resId > 0) {
			return mContext.getString(resId);
		}
		return null;
	}
}
